package com.agrm.rabc.service.impl;


import com.agrm.model.rabc.dto.UserGroupMapping;
import com.agrm.rabc.mapper.UserGroupMappingDao;
import com.agrm.rabc.service.GroupService;
import com.agrm.rabc.service.UserGroupMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;


@CacheConfig(cacheNames = "c.s.r.s.impl.UserGroupMappingServiceImpl")
@Service
public class UserGroupMappingServiceImpl implements UserGroupMappingService {
    private UserGroupMappingDao userGroupMappingDao;
    private GroupService groupService;

    @Autowired
    public void setUserGroupMappingDao(UserGroupMappingDao userGroupMappingDao) {
        this.userGroupMappingDao = userGroupMappingDao;
    }

    @Autowired
    public void setGroupService(GroupService groupService) {
        this.groupService = groupService;
    }

    @Cacheable(keyGenerator = "customKeyGenerator")
    @Override
    public List<UserGroupMapping> findAll(UserGroupMapping ugm) {
        List<UserGroupMapping> mappings = userGroupMappingDao.findAll(ugm);
        mappings.forEach(it -> {
            it.setGroup(this.groupService.findById(it.getGroupId()));
        });
        return mappings;
    }

    @Cacheable(key = "#p0")
    @Override
    public UserGroupMapping findById(Integer id) {
        UserGroupMapping mapping = userGroupMappingDao.selectById(id);
        mapping.setGroup(this.groupService.findById(mapping.getGroupId()));
        return mapping;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(UserGroupMapping ugm) {
        return userGroupMappingDao.insert(ugm) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(UserGroupMapping ugm) {
        return userGroupMappingDao.updateById(ugm) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteByIds(List<Integer> ids) {
        return userGroupMappingDao.deleteByIds(ids);
    }
}
